﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crude.Common;
using System.IO;

namespace Crude.Core.Repository
{
    public class FileSystemRemoteRepository : FileSystemRepository, IRemoteRepository
    {
        public string m_localRepositoryPath;

        internal FileSystemRemoteRepository(string remoteRepositoryPath,
            string localRepositoryPath)
            : base(remoteRepositoryPath)
        {
            m_localRepositoryPath = localRepositoryPath;
        }

        public void DownloadAssmebly(ProjectObjectModel pom)
        {
            string remoteDirectoryLocation =
                string.Format("{0}\\{1}\\{2}", RepositoryPath, pom.Name, pom.Version);

            string localDirectoryLocation =
                string.Format("{0}\\{1}\\{2}", m_localRepositoryPath, pom.Name, pom.Version);

            FileSystemUtility.CopyFolder(remoteDirectoryLocation, localDirectoryLocation);
        }

        public IList<ProjectObjectModel> GetProjectAvailableVersions(string projectName)
        {
            List<Version> versions = new List<Version>();

            string projectPath = string.Format("{0}\\{1}", RepositoryPath, projectName);

            if (Directory.Exists(projectPath))
            {
                string[] projectVersions = Directory.GetDirectories(projectPath);

                foreach (string projectVersion in projectVersions)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(projectVersion);

                    Version version = Version.Parse(directoryInfo.Name);

                    if (!versions.Contains(version))
                    {
                        versions.Add(version);
                    }
                }
            }

            versions =  versions.OrderBy(v => v).ToList();

            return (from verion in versions
                    select GetProjectObjectModel(
                    new ProjectDependency { Name = projectName, Version = verion.ToString() })).ToList();
        }

        public IList<string> GetAllProjectNames()
        {
            return (
                from string projectPath in Directory.GetDirectories(RepositoryPath)
                    select new DirectoryInfo(projectPath).Name).ToList();
        }
    }
}
